package com.db.httpserver;

import java.io.IOException;
import java.io.PrintStream;
import java.net.ConnectException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class NetClient implements Runnable {

	private Socket requestSocket;
	private PrintStream out;
	private Scanner in;
	private int port;

	NetClient(int port) {
		this.port = port;
	}

	@Override
	public void run() {

		try {
			requestSocket = new Socket("localhost", port);
			requestSocket.setSoTimeout(Parameter.getTimeout() );
			out = new PrintStream(requestSocket.getOutputStream(), true);
			in = new Scanner(requestSocket.getInputStream());
			
			out.print("GET / HTTP/1.0\r\nHost: localhost:8081");
			
			while (in.hasNextLine()) {
				in.nextLine();
			}
			
		} catch (UnknownHostException unknownHost) {
			System.out.println("You are trying to connect to an unknown host!");
		} catch (ConnectException conExc) {
			System.out.println(conExc.getMessage());
		} catch (NullPointerException nullExc) {
			System.out.println(nullExc.getMessage());
		} catch (IOException ioException) {
			ioException.printStackTrace();
		} finally {
			try {
				in.close();
				out.close();
				requestSocket.close();
			} catch (IOException ioException) {
				ioException.printStackTrace();
			} catch (NullPointerException nullExc) {
				System.out.println(nullExc.getMessage());
			}
		}
	}
}
